package imclient.handler;

import com.alibaba.fastjson.JSON;
import com.tee.im.constants.AppIdEnum;
import com.tee.im.constants.ImMsgCodeEnum;
import com.tee.im.dto.ImMsgBody;
import com.tee.im.interfaces.ImTokenRpc;
import com.tee.live.im.core.server.common.ImMsg;
import com.tee.live.im.core.server.common.ImMsgDecode;
import com.tee.live.im.core.server.common.ImMsgEncode;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class ImClientHandler implements InitializingBean {

    @DubboReference
    private ImTokenRpc imTokenRpc;

    @Override public void afterPropertiesSet() throws Exception {

        Thread clientThread = new Thread(() -> {
            NioEventLoopGroup clientGroup = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(clientGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<>() {
                @Override
                protected void initChannel(Channel channel) throws Exception {

                    channel.pipeline()
                        .addLast(new ImMsgEncode());
                    channel.pipeline()
                        .addLast(new ImMsgDecode());
                    channel.pipeline()
                        .addLast(new ClientHandler());
                }
            });

            HashMap<Long, Channel> userIdChannelMap = new HashMap<>();
            for (int i = 0; i < 10; i++) {
                Long userId = 100000L+i;
                String token = imTokenRpc.createImLoginToken(userId, AppIdEnum.SY_LIVE_BIZ.getCode());
                ChannelFuture sync = null;
                try {
                    sync = bootstrap.connect("127.0.0.1", 8085)
                        .sync();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Channel channel = sync.channel();
                ImMsgBody imMsgBody = new ImMsgBody();
                imMsgBody.setAppId(AppIdEnum.SY_LIVE_BIZ.getCode());
                imMsgBody.setUserId(userId);
                imMsgBody.setToken(token);
                ImMsg loginMsg = ImMsg.build(ImMsgCodeEnum.IM_LOGIN_MSG.getCode(), JSON.toJSONString(imMsgBody));
                loginMsg.setBody(JSON.toJSONBytes(imMsgBody));
                channel.writeAndFlush(loginMsg);
                userIdChannelMap.put(userId, channel);
            }

            while (true) {
                for (final Long userId : userIdChannelMap.keySet()) {
                    ImMsgBody heartBeatBody = new ImMsgBody();
                    heartBeatBody.setAppId(AppIdEnum.SY_LIVE_BIZ.getCode());
                    heartBeatBody.setUserId(userId);
                    ImMsg heartBeatMsg = ImMsg.build(ImMsgCodeEnum.IM_HEARTBEAT_MSG.getCode(), JSON.toJSONString(heartBeatBody));
                    userIdChannelMap.get(userId).writeAndFlush(heartBeatMsg);
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        clientThread.start();
    }

}
